package com.LeeCode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 统计数组中相等且可以被整除的数对
 */

public class Code2176 {
    public static void main(String[] args) {
        int[] nums = {3, 1, 2, 2, 2, 1, 3};
        int k = 2;
        System.out.println(new Code2176().countPairs1(nums, k));
    }

    public int countPairs(int[] nums, int k) {
        int ans = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j] && (i * j) % k == 0) {
                    ans++;
                }
            }
        }
        return ans;
    }

    public int countPairs1(int[] nums, int k) {
        int ans = 0;
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int val = nums[i];
            for(int index: map.getOrDefault(val, new ArrayList<Integer>())){
                if((index * i) % k == 0){
                    ans++;
                }
            }
            if(map.containsKey(val)){
                map.get(val).add(i);
            }else{
                List<Integer> list = new ArrayList<>();
                list.add(i);
                map.put(val, list);
            }
        }
        return ans;
    }
}
